package com.compass.doctor.ui.patient

import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.databinding.ActivityDiagnoseBinding
import com.compass.doctor.dialog.AppendDiagnoseDialog
import com.compass.doctor.ui.home.adapter.ExecutiveDepartmentAdapter
import com.compass.doctor.ui.patient.viewmodel.ExamineViewModel
import com.compass.framework.decoration.NormalItemDecoration
import com.compass.framework.ext.gone
import com.compass.framework.ext.onClick
import com.compass.framework.ext.textChangeFlow
import com.compass.framework.ext.visible
import com.compass.framework.model.InpatientWard
import com.compass.framework.utils.dpToPx
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

/**
 * Description： 科室
 * Date:2024/3/29 18:17
 */
class InpatientDepartmentActivity : BaseVBActivity<ActivityDiagnoseBinding>() {


    private val examineViewModel: ExamineViewModel by viewModels()
    private lateinit var mAdapter: ExecutiveDepartmentAdapter
    private var searchList: ArrayList<InpatientWard> = ArrayList()//搜索出来的 科室名称（病区）
    private var inpatientList: ArrayList<InpatientWard> = ArrayList()//科室名称（病区）
    override fun initView(savedInstanceState: Bundle?) {
        mBinding.tvTitleBar.setMiddleText("住院科室")
        mBinding.edtDiagnosis.hint="请输入科室关键字"

        mBinding.edtDiagnosis.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                val keyWord = mBinding.edtDiagnosis.text.toString().trim()
                searchDepartment(keyWord)
            }
            false
        }
        mBinding.tvTitleBar.getRightLayout().onClick {
            AppendDiagnoseDialog.Builder(this).show()
        }


//        mBinding.edtDiagnosis.textChangeFlow()
//            .distinctUntilChanged()
//            .debounce(500)
//            .flowOn(Dispatchers.IO)
//            .onEach {
//                //这里走查询接口
//                searchDepartment(mBinding.edtDiagnosis.text.toString().trim())
//
//            }
//            .launchIn(lifecycleScope)


        initRecyclerView()
    }
    private fun searchDepartment(kayWords: String) {
        searchList.clear()
        if (kayWords.isNotEmpty()) {
            for (item in inpatientList) {
                if (item.name.contains(kayWords)) {
                    searchList.add(item)
                }
            }
            mAdapter.setData(searchList)
            if (searchList.isNotEmpty())  mBinding.recyclerView.visible() else mBinding.recyclerView.gone()
        }


    }
    override fun initData() {
        examineViewModel.getInpatientWardList()
        examineViewModel.inpatientLiveData.observe(this) {
            dismissLoading()

            if (it.isNullOrEmpty()){
                mBinding.emptyView.visible()
                mAdapter.setData(null)
            }else{
                inpatientList=it as ArrayList<InpatientWard>
                mBinding.emptyView.gone()
                mAdapter.setData(it)
            }
        }

    }

    override fun intListener() {
        mBinding.btnSearch.onClick {
            val keyWord = mBinding.edtDiagnosis.text.toString().trim()
            searchDepartment(keyWord)
        }
        mBinding.edtDiagnosis.addTextChangedListener {
            if (it.toString().isEmpty()) {
                mAdapter.setData(inpatientList)
            }

        }
    }



    private fun initRecyclerView() {
        mBinding.refreshLayout.apply {
            setEnableRefresh(false)
            setEnableLoadMore(false)

        }
        mAdapter = ExecutiveDepartmentAdapter()
        val dp1 = dpToPx(1)
        mBinding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            addItemDecoration(NormalItemDecoration().apply {
                setBounds(top = dp1, bottom = dp1)
                setLastBottom(true)

            })
            adapter = mAdapter
        }
        mAdapter.onItemClickListener = { _: View, position: Int ->
            val item = mAdapter.getItem(position)
            item?.let {
                intent.putExtra("department",item)
                setResult(RESULT_OK, intent)
                finish()
            }

        }

    }
}